package webbandidong.controller.accountcontroller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import webbandidong.auth.AuthAdminSimpleFormController;
import webbandidong.bo.impl.AdminBOImpl;
import webbandidong.model.Admin;
import webbandidong.util.Constant;
import webbandidong.viewmodel.AdminChangePassViewModel;

public class AdminChangePasswordController extends AuthAdminSimpleFormController {
    @Autowired
    private AdminBOImpl adminBOImpl;

    public void setAdminBOImpl(AdminBOImpl adminBOImpl) {
        this.adminBOImpl = adminBOImpl;
    }

    public AdminChangePasswordController() {

        setCommandClass(AdminChangePassViewModel.class);
        setCommandName("adminChangePassViewModel");
        setSuccessView("admin/account/adminchangepass");
        setFormView("admin/account/adminchangepass");
    }

    @Override
    public ModelAndView onAuthSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {
        AdminChangePassViewModel model = (AdminChangePassViewModel)command;
        int id = (Integer)request.getSession().getAttribute(Constant.USER_ID);
        String username = (String)request.getSession().getAttribute(Constant.USER_NAME);
        String status = adminBOImpl.updateAdmin(new Admin(id, username, model.getNewPassword()));
        response.sendRedirect("/admin/changepass.htm?status=" + status);
        return null;
//        return new ModelAndView(getSuccessView());
//        return showForm(request, response, errors);
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        AdminChangePassViewModel model = new AdminChangePassViewModel();
        model.setUsername((String)request.getSession().getAttribute(Constant.USER_NAME));
        return model;
    }
}